package com.srwl.mytx.tao.av;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Area;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.os.Build.VERSION;
import android.view.SurfaceHolder;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

//import com.taobao.av.util.SystemUtil;

public class CameraHelper {
    public CameraHelper() {
    }

    public static int findCameraByFacing(int facing) {
        CameraInfo info = new CameraInfo();
        int i = 0;

        for(int len = Camera.getNumberOfCameras(); i < len; ++i) {
            Camera.getCameraInfo(i, info);
            if (info.facing == facing) {
                return i;
            }
        }

        return -1;
    }

    public static Camera openCamera(int id) {
        try {
            return Camera.open(id);
        } catch (Throwable var2) {
            return null;
        }
    }

    public static Camera openCameraByFacing(int facing) {
        int i = findCameraByFacing(facing);
        return i < 0 ? null : openCamera(i);
    }

    public static boolean hasCameraFacing(int facing) {
        return findCameraByFacing(facing) >= 0;
    }

    public int getCameraRotation(int id) {
        CameraInfo cameraInfo2 = new CameraInfo();
        Camera.getCameraInfo(id, cameraInfo2);
        return cameraInfo2.orientation;
    }

    public boolean getCameraMirrored(int id) {
        CameraInfo cameraInfo2 = new CameraInfo();
        Camera.getCameraInfo(id, cameraInfo2);
        return cameraInfo2.facing == 1;
    }

    public static int getDisplayRotation(Context context) {
        WindowManager wm = (WindowManager)context.getSystemService("window");
        int rotation_id = wm.getDefaultDisplay().getRotation();
        int rotation = 0;
        switch(rotation_id) {
            case 0:
                rotation = 0;
                break;
            case 1:
                rotation = 90;
                break;
            case 2:
                rotation = 180;
                break;
            case 3:
                rotation = 270;
        }

        return rotation;
    }

    public static int getCameraDisplayOrientation(int display_rotation, CameraInfo info) {
        int result;
        if (info.facing == 1) {
            result = (info.orientation + display_rotation) % 360;
            result = (360 - result) % 360;
        } else {
            result = (info.orientation - display_rotation + 360) % 360;
        }

        return result;
    }

    public static int getCameraDisplayOrientation(Context context, CameraInfo info) {
        int display_rotation = getDisplayRotation(context);
        return getCameraDisplayOrientation(display_rotation, info);
    }

    public static void setCameraDisplayOrientation(Context context, Camera camera, CameraInfo info) {
        int result = getCameraDisplayOrientation(context, info);
        camera.setDisplayOrientation(result);
    }

    public static void setCameraDisplayOrientation(Context context, int id, Camera camera) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(id, info);
        setCameraDisplayOrientation(context, camera, info);
    }

    public static int getFacingBackDegrees(Activity activity, int cameraId) {
        if (cameraId == SystemUtil.getCameraFacingFront()) {
            return 270;
        } else {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(cameraId, info);
            int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            int degrees = 0;
            switch(rotation) {
                case 0:
                    degrees = 0;
                    break;
                case 1:
                    degrees = 90;
                    break;
                case 2:
                    degrees = 180;
                    break;
                case 3:
                    degrees = 270;
            }

            int result = (info.orientation - degrees + 360) % 360;
            return result;
        }
    }

    public static Size choosePreviewSizeByProfile(Parameters params, int width, int height) {
        List<Size> size_list = params.getSupportedPreviewSizes();
        Size valid_list = null;
        Iterator i$ = size_list.iterator();

        while(i$.hasNext()) {
            Size item = (Size)i$.next();
            if (item.width == width && item.height == height) {
                valid_list = item;
                break;
            }
        }

        return valid_list;
    }

    public static Size[] choosePreviewSize(Parameters params, int width, int height) {
        List<Size> size_list = params.getSupportedPreviewSizes();
        ArrayList<Size> valid_list = new ArrayList();
        Iterator i$ = size_list.iterator();

        while(i$.hasNext()) {
            Size item = (Size)i$.next();
            if (item.width >= width && item.height >= height && item.height != item.width) {
                valid_list.add(item);
            }
        }

        Size[] size_array = (Size[])valid_list.toArray(new Size[0]);
        Arrays.sort(size_array, new Comparator<Size>() {
            public int compare(Size lhs, Size rhs) {
                return lhs.width * lhs.height - rhs.width * rhs.height;
            }
        });
        return size_array;
    }

    @SuppressLint({"NewApi"})
    public static Size choosePreviewSizeByUser(Parameters params, int width, int height) {
        List<Size> size_list = null;
        if (VERSION.SDK_INT >= 11) {
            size_list = params.getSupportedVideoSizes();
        }

        if (size_list == null) {
            size_list = params.getSupportedPreviewSizes();
        }

        if (size_list == null) {
            return null;
        } else {
            ArrayList<Size> valid_list = new ArrayList();
            Iterator i$ = size_list.iterator();

            while(i$.hasNext()) {
                Size item = (Size)i$.next();
                if (item.width >= width && item.height >= height && item.height != item.width) {
                    valid_list.add(item);
                }
            }

            Size[] size_array = (Size[])valid_list.toArray(new Size[0]);
            Arrays.sort(size_array, new Comparator<Size>() {
                public int compare(Size lhs, Size rhs) {
                    return lhs.width * lhs.height - rhs.width * rhs.height;
                }
            });
            return size_array[0];
        }
    }

    @SuppressLint({"NewApi"})
    public static void setupAutoBalanceLock(Parameters cameraParams) {
        if (VERSION.SDK_INT >= 14) {
            if (cameraParams.isAutoWhiteBalanceLockSupported()) {
                cameraParams.setAutoWhiteBalanceLock(true);
            }
        }
    }

    @SuppressLint({"NewApi"})
    public static void setupVideoStabilization(Parameters cameraParams) {
        if (VERSION.SDK_INT >= 15) {
            if (cameraParams.isVideoStabilizationSupported()) {
                cameraParams.setVideoStabilization(true);
            }
        }
    }

    public static void setupCameraSurface(SurfaceHolder holder) {
        if (VERSION.SDK_INT < 11) {
            holder.setType(3);
        }
    }

    public static void setPreviewFrameRate5(Parameters params, final int frameRate) {
        List<Integer> supported_list = params.getSupportedPreviewFrameRates();
        Collections.sort(supported_list, new Comparator<Integer>() {
            private int getScore(int value) {
                return -Math.abs(value - frameRate);
            }

            public int compare(Integer lhs, Integer rhs) {
                return this.getScore(rhs) - this.getScore(lhs);
            }
        });
        params.setPreviewFrameRate((Integer)supported_list.get(0));
    }

    public static void setPreviewFrameRate9(Parameters params, final int target_fps) {
        List<int[]> supported_list = params.getSupportedPreviewFpsRange();
        Collections.sort(supported_list, new Comparator<int[]>() {
            private int getScore(int[] value) {
                if (value[0] > target_fps) {
                    return -value[0];
                } else {
                    return value[1] < target_fps ? -value[1] : target_fps - (value[1] - value[0]);
                }
            }

            public int compare(int[] lhs, int[] rhs) {
                return this.getScore(rhs) - this.getScore(lhs);
            }
        });
        int[] value = (int[])supported_list.get(0);
        params.setPreviewFpsRange(value[0], value[1]);
    }

    public static void setPreviewFrameRate(Parameters params, int frameRate) {
        int target_fps = frameRate * 1000;
        setPreviewFrameRate5(params, frameRate);
        if (VERSION.SDK_INT >= 9) {
            setPreviewFrameRate9(params, target_fps);
        }

    }

    public static String findString(List<String> list, String... candidate_list) {
        String[] arr$ = candidate_list;
        int len$ = candidate_list.length;

        for(int i$ = 0; i$ < len$; ++i$) {
            String item = arr$[i$];
            if (list.contains(item)) {
                return item;
            }
        }

        return null;
    }

    public static String chooseFocusMode(Parameters params) {
        return findString(params.getSupportedFocusModes(), "continuous-video", "continuous-picture", "auto");
    }

    public static String setFocusMode(Parameters params) {
        String mode = chooseFocusMode(params);
        if (mode != null) {
            params.setFocusMode(mode);
        }

        return mode;
    }

    @TargetApi(14)
    public static void setFocusArea(Parameters params, Rect rect) {
        if (VERSION.SDK_INT >= 14) {
            Area focus_area = new Area(rect, 1);
            int focus_area_count_max = params.getMaxNumFocusAreas();
            if (focus_area_count_max >= 1) {
                params.setFocusAreas(Arrays.asList(focus_area));
            }
        }
    }

    public static String chooseFlashlightMode(Parameters params, boolean enabled) {
        List<String> supported_list = params.getSupportedFlashModes();
        if (supported_list == null) {
            return null;
        } else {
            return enabled ? findString(supported_list, "torch", "on", "red-eye", "auto") : findString(supported_list, "off", "auto");
        }
    }

    public static boolean isFlashlightSupported(Parameters params) {
        return chooseFlashlightMode(params, true) != null;
    }

    public static String setFlashlightMode(Parameters params, boolean enabled) {
        String mode = chooseFlashlightMode(params, enabled);
        if (mode != null) {
            params.setFlashMode(mode);
        }

        return mode;
    }

    public static boolean getFlashlightOn(Parameters params) {
        String mode = params.getFlashMode();
        return mode != null && !mode.equals("off");
    }

    public static void getSurfaceToPreviewDataTransform(Matrix m, int camera_display_orientation, int camera_facing, int preview_width, int preview_height) {
        float half_w = (float)preview_width / 2.0F;
        float half_h = (float)preview_height / 2.0F;
        m.reset();
        switch(camera_display_orientation) {
            case 90:
            case 270:
                m.setTranslate(-half_h, -half_w);
                break;
            default:
                m.setTranslate(-half_w, -half_h);
        }

        m.postRotate((float)(-camera_display_orientation));
        if (camera_facing == 1) {
            m.postScale(-1.0F, 1.0F);
        }

        m.postTranslate(half_w, half_h);
    }
}

